<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <router-link :to="'/wxmini/section?menuId=' + this.menuId" class="link-type">
          <el-button icon="el-icon-back" size="mini">
            返 回
          </el-button>
        </router-link>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['module:sectionlinks:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['module:sectionlinks:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['module:sectionlinks:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="linksList" @selection-change="handleSelectionChange">
      <el-table-column label="图片" align="center">
        <template slot-scope="scope">
          <a :href="scope.row.imgUrlPath" target="_blank" v-if="scope.row.imgUrlPath!=null && scope.row.imgUrlPath!=''">
            <img :src="scope.row.imgUrlPath" title="点击打开" style="width: 60px;height: 60px;">
          </a>
        </template>
      </el-table-column>
      <el-table-column label="内嵌ICON" align="center">
        <template slot-scope="scope">
          <a :href="scope.row.iconUrlPath" target="_blank" v-if="scope.row.iconUrlPath!=null && scope.row.iconUrlPath!=''">
            <img :src="scope.row.iconUrlPath" title="点击打开" style="width: 100px;height: 60px;">
          </a>
        </template>
      </el-table-column>
      <el-table-column label="附带文字" align="center" prop="btnText" />
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <div>
            <el-tag v-if="scope.row.state === 0" style="cursor: pointer" :type="''">显示</el-tag>
            <el-tag v-else style="cursor: pointer" :type=" 'info' ">停用</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="链接类型" align="center" prop="linkTypeName" />

      <el-table-column label="链接地址" align="center" prop="linkUrl" />
      <el-table-column label="排序索引" align="center" prop="sort" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['module:sectionlinks:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['module:sectionlinks:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"/>

    <!-- 添加或修改每个内容行里的数据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="550px" append-to-body>

      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="链接内容类型" prop="linkType">
          <el-select v-model="form.linkType" placeholder="请选择链接内容类型" size="mini" @change="selectLinkType">
            <el-option v-for="dict in linkTypeOptions"
                       :key="dict.dictValue"
                       :label="dict.dictLabel"
                       :value="dict.dictValue"/>
          </el-select>
        </el-form-item>

        <el-form-item label="图片" prop="imgUrlPath" >
          <single-pic v-model="form.imgUrlPath" type="image" @handleChecked="chooseImg" :uploadType="2" :num="1" :width="200" :height="110" />
        </el-form-item>
        <el-form-item label="内嵌ICON图标" prop="iconUrlPath" >
          <single-pic v-model="form.iconUrlPath" type="image" @handleChecked="chooseIconImg" :uploadType="2" :num="1" :width="100" :height="100" />
        </el-form-item>

        <el-form-item label="广告类型" prop="linkId" v-if="form.linkType ==='advert'">
          <el-col :span="15">
            <el-select v-model="form.linkId" placeholder="请选择广告类型" size="mini" @change="handleCate">
              <el-option v-for="dict in bannerTypeOptions"
                         :key="dict.dictValue"
                         :label="dict.dictLabel"
                         :value="parseInt(dict.dictValue)"/>
            </el-select>
          </el-col>
          <el-col :span="5">
            <el-button type="primary" @click="getBannerList" size="mini">选择广告</el-button>
          </el-col>

          <el-col :span="12" v-if="banner !== undefined && banner.id > 0">
            <el-card :body-style="{ padding: '0px',}">
              <img :src="banner.imgPath" class="image">
            </el-card>
          </el-col>
        </el-form-item>

        <el-row v-if="form.linkType ==='coupons'">
<!--          <el-form-item label="优惠券" prop="linkId" >-->
<!--            <el-select v-model="form.linkId" placeholder="请选择优惠券" filterable  size="mini">-->
<!--              <el-option v-for="coupon in couponsOptions"-->
<!--                         :key="coupon.id"-->
<!--                         :label="coupon.couponName"-->
<!--                         :value="coupon.id"/>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
          <el-form-item label="内置页面" prop="linkUrl" >
            <el-input v-model="form.linkUrl" size="mini" placeholder="请输入内置页面地址" style="width:60%;"/>
          </el-form-item>
        </el-row>

        <el-row v-if="form.linkType ==='product'">
          <el-form-item label="商品分类" prop="linkId" >
            <el-col :span="15">
              <el-select v-model="queryParamsGoods.cateChildId" placeholder="请选择商品分类" filterable  size="mini" @change="handleCate">
                <el-option v-for="type in productTypeOptions"
                           :key="type.id"
                           :label="type.typeName + '(商品数：'+ type.productCount + '个)'"
                           :value="type.id"/>
              </el-select>
            </el-col>
            <el-col :span="5">
              <el-button type="primary" size="mini" @click="handleSectionGoods">选择商品/服务</el-button>
            </el-col>
            <el-col :span="10" v-if="product!== undefined && product.id > 0">
              <el-card :body-style="{ padding: '0px',height:'260px' }">
                <img :src="product.imagePath" class="image">
                <div style="line-height: 25px;">
                  <el-row class="card-view-text">
                    <span style="font-size: 12px;">【{{product.merName}}】</span>
                  </el-row>
                  <el-row class="card-view-text">
                    <span style="font-size: 12px;">{{product.storeName}}</span>
                  </el-row>
                  <el-row class="card-view-text">
                    <span style="font-size: 12px;">{{product.storeInfo}}</span>
                  </el-row>
                </div>
              </el-card>
            </el-col>
          </el-form-item>
        </el-row>

        <el-row v-if="form.linkType ==='product_type'">
          <el-form-item label="商品分类" prop="linkId" >
            <el-col :span="24">
              <el-select v-model="form.linkId" placeholder="请选择商品分类" filterable  size="mini" @change="handleCate">
                <el-option v-for="type in productTypeOptions"
                           :key="type.id"
                           :label="type.typeName + '(商品数：'+ type.productCount + '个)'"
                           :value="type.id"/>
              </el-select>
            </el-col>
          </el-form-item>
        </el-row>

        <el-row v-if="form.linkType ==='page'">
          <el-form-item label="内置页面" prop="linkUrl" >
            <el-input v-model="form.linkUrl" size="mini" placeholder="请输入内置页面地址" style="width:60%;"/>
          </el-form-item>

          <el-form-item label="是否底部菜单" prop="isSwitchTab">
            <el-radio-group v-model="form.isSwitchTab" size="mini">
              <el-radio :value="0" :label="0">否</el-radio>
              <el-radio :value="1" :label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>

        <el-form-item label="附带文字" prop="btnText">
          <el-input v-model="form.btnText"  size="mini" placeholder="请输入附带文字"/>
        </el-form-item>


        <el-form-item label="附带文字样式" prop="btnTextCss">
          <el-input v-model="form.btnTextCss" size="mini" placeholder="请输入附带文字样式"/>
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="排序索引" prop="sort">
              <el-input v-model="form.sort" type="number" size="mini" placeholder="请输入排序索引" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="state">
              <el-radio-group v-model="form.state" size="mini">
                <el-radio :value="0" :label="0">正常</el-radio>
                <el-radio :value="1" :label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" size="mini" @click="submitForm">确 定</el-button>
        <el-button @click="cancel" size="mini">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="titleGoods" :visible.sync="openGoods" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商家名称" prop="storeName">
              <el-select v-model="form.linkKey" placeholder="请选择商家名称" size="mini" filterable  style="width:100%;" @change="selectMer">
                <el-option v-for="mer in merList"
                           :key="mer.id"
                           :label="mer.shopName + '(商品数：'+ mer.productCount + '个)'"
                           :value="mer.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryGoods">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6" v-for="product in productList" style="padding: 10px;">
            <el-card :body-style="{ padding: '10px',height:'230px' }">
              <img :src="product.imagePath" class="image" style="height:100px;">
              <div style="line-height: 25px;">
                <el-row class="card-view-text">
                  <span style="font-size: 12px;">【{{product.merName}}】</span>
                </el-row>
                <el-row class="card-view-text">
                  <span style="font-size: 12px;">{{product.storeName}}</span>
                </el-row>
                <el-row class="card-view-text">
                  <span style="font-size: 12px;">{{product.storeInfo}}</span>
                </el-row>
                <div class="bottom clearfix">
                  <el-button type="text" class="button" size="mini" @click="chooseProduct(product)">选择</el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <pagination v-show="totalGoods > 0"
                    :total="totalGoods"
                    :page.sync="queryParamsGoods.pageNum"
                    :limit.sync="queryParamsGoods.pageSize"
                    @pagination="getGoodsList" />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="openGoods = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="titleBanner" :visible.sync="openBanners" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="7" v-for="banner in bannerList" style="margin-left: 20px;">
            <el-card :body-style="{ padding: '0px', }">
              <img :src="banner.imgPath" class="image">
              <div style="padding: 5px 15px;">
                <div class="bottom clearfix">
                  <el-button type="text" class="button" size="mini" @click="chooseBanner(banner)">选择</el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <pagination v-show="totalBanners > 0"
                    :total="totalBanners"
                    :page.sync="queryParamsBanner.pageNum"
                    :limit.sync="queryParamsBanner.pageSize"
                    @pagination="getBannerList" />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="openBanners = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLinks, getLinks, delLinks, addLinks, updateLinks } from "@/api/module/titlemenu/links";
import Treeselect from "@riophae/vue-treeselect";
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import { listProduct } from "@/api/module/product/list";
import { listBanner } from "@/api/module/banner";
import { listMer} from "@/api/module/mer/mer";


import { listCoupons } from "@/api/module/coupons/coupons";

import singlePic from '@/components/SingleMaterial';
import { listAll } from "@/api/module/product/type";

export default {
  name: "Links",
  components: {  Treeselect, singlePic},
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      menuId:0,
      totalGoods:0,
      totalBanners:0,
      // 每个内容行里的数据表格数据
      linksList: [],
      linkTypeOptions:[],
      couponsOptions:[],
      // 弹出层标题
      title: "",
      titleBanner:"",
      // 是否显示弹出层
      open: false,
      // 弹出层标题
      titleGoods: "",
      // 是否显示弹出层
      openGoods: false,
      openBanners:false,
      productList:[],
      bannerList:[],
      productTypeOptions:[],
      bannerTypeOptions:[],
      merList:[],
      sectionId:0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sectionId:0
      },
      formGoods:{},
      // 查询参数
      queryParamsGoods: {
        pageNum: 1,
        pageSize: 8,
        merId:undefined,
        cateChildId:undefined,
        sectionId:undefined,
        isShow:1,
      },
      // 查询参数
      queryParamsBanner: {
        pageNum: 1,
        pageSize: 10,
      },
      // 查询参数
      queryParamsMer: {
        pageNum: 1,
        pageSize: 100,
        cateChildId:undefined,
        isShowProduct:1,
      },
      // 查询参数
      queryParamsPType: {
        parentId:0,
      },
      // 查询参数
      queryParamsCoupons: {
        pageNum: 1,
        pageSize: 100,
        state:0,
      },
      product:{},
      banner:{},
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    console.log('section  this.$route.query',this.$route.query);
    this.sectionId = this.$route.query.sectionId ? this.$route.query.sectionId : 0;
    this.menuId = this.$route.query.menuId ? this.$route.query.menuId : 0;
    this.queryParams.sectionId = this.sectionId;
    this.getList();
    this.getDicts("link_type").then(response => {
      this.linkTypeOptions = response.data;
    });
    this.getDicts("banner_type").then(response => {
      this.bannerTypeOptions = response.data;
    });

    this.getProductTypeList();
    // this.getCouponsList();
  },
  methods: {
    /** 查询每个内容行里的数据列表 */
    getList() {
      this.loading = true;
      listLinks(this.queryParams).then(response => {
        this.linksList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    selectLinkType(val){
      console.log('selectLinkType',val);
    },
    chooseImg(data){
      console.log("menu chooseImg",data);
      if(data.length > 0) {
        this.form.imgUrlPath = data[0].imgUrl;
        this.form.imgUrl = data[0].url;
      }
    },
    getProductTypeList() {
      listAll(this.queryParamsPType).then(res => {
        this.productTypeOptions = res.data;
      })
    },
    getMerList() {
      this.queryParamsMer.pageSize = 10000;
      listMer(this.queryParamsMer).then(response => {
        this.merList = response.rows;
      });
    },
    getCouponsList(){
      listCoupons(this.queryParamsCoupons).then(response => {
        this.couponsOptions = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        sectionId: this.sectionId,
        imgUrl: undefined,
        imgUrlPath: undefined,
        iconUrl:undefined,
        iconUrlPath:undefined,
        viewHeight: undefined,
        viewWidth: undefined,
        linkType: undefined,
        linkId: undefined,
        linkUrl: undefined,
        isSwitchTab:0,
        maskType: undefined,
        sort: undefined,
        state: undefined,
        maskImg: undefined,
        labelText: undefined,
        btnText:undefined,
        btnTextCss:undefined,
      };
      this.resetForm("form");
    },
    handleCate(val){
      console.log('handleCate',val);
      this.queryParamsGoods.cateChildId = val;
      this.queryParamsMer.cateChildId = val;
    },
    selectMer(val){
      console.log('selectMer',val);
      this.queryParamsGoods.merId = val;
    },
    handleQueryGoods() {
      this.queryParamsGoods.pageNum = 1;
      // this.queryParamsGoods.merId =
      // this.getMerList();
      this.getGoodsList();
    },
    handleSectionGoods(){
      this.openGoods = true;
      this.titleGoods = "绑定商品";
      this.getMerList();
      this.getGoodsList();
    },
    /** 查询商品列表 */
    getGoodsList() {
      this.productList = [];
      listProduct(this.queryParamsGoods).then(response => {
        console.log('getGoodsList',response.rows);
        this.productList = response.rows;
        this.totalGoods = response.total;
      });
    },
    getBannerList(){
      this.bannerList = [];
      this.totalBanners = 0;
      this.openBanners = true;
      listBanner(this.queryParamsBanner).then(response => {
        console.log('getGoodsList',response.rows);
        this.bannerList = response.rows;
        this.totalBanners = response.total;
      });
    },
    chooseIconImg(data){
      console.log("menu chooseIconImg",data);
      if(data.length > 0) {
        this.form.iconUrlPath = data[0].imgUrl;
        this.form.iconUrl = data[0].url;
      }
    },
    chooseProduct(product){
      console.log('product',product);
      this.queryParamsGoods.cateChildId = product.cateChildId;
      this.queryParamsMer.cateChildId = product.cateChildId;

      this.form.linkId = product.id;
      this.openGoods = false;
      this.product = product;
    },
    chooseBanner(banner){
      console.log('banner',banner);
      // this.queryParamsBanner.cateId = product.cateId;
      this.form.linkId = banner.id;
      this.openBanners = false;
      this.banner = banner;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length!==1;
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加每个内容行里的数据";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids;
      getLinks(id).then(response => {
        this.loading = false;
        this.form = response.data;
        console.log('this.form.product',this.form.product);
        console.log('this.form',this.form);
        if(this.form.product !== undefined && this.form.product!== null && this.form.product!== 'null'){
          this.queryParamsGoods.cateChildId = this.form.product.cateChildId;
          this.queryParamsMer.cateChildId = this.form.product.cateChildId;
          console.log('this.form.product 111',this.form.product);
          this.product = this.form.product;
        }
        if(this.form.banner!==undefined && this.form.banner!== null && this.form.banner!== 'null'){
          console.log('this.form.banner222',this.form.banner);
          this.banner = this.form.banner;
        }
        this.open = true;
        this.title = "修改每个内容行里的数据";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateLinks(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addLinks(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除每个内容行里的数据编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.loading = true;
          return delLinks(ids);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
  }
};
</script>

<style>
  .time {
    font-size: 13px;
    color: #999;
  }

  .bottom {
    line-height: 12px;
  }

  .button {
    padding: 0;
    float: right;
  }

  .image {
    width: 100%;
    height: 150px;
    display: block;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
    clear: both
  }

  .card-view-text{
    text-overflow: ellipsis;
    overflow: hidden;
    text-overflow:ellipsis;
    white-space: nowrap;
  }
</style>
